const vscode = require('vscode');
const ProjectAnalyzer = require('./projectAnalyzer');
const CodeGenerator = require('./codeGenerator');
const AIService = require('./aiService');

class AgentManager {
    constructor() {
        this.analyzer = new ProjectAnalyzer();
        this.generator = new CodeGenerator(this.analyzer);
        this.aiService = new AIService();
        this.context = {};
        this.workspaceRoot = '';
    }

    async initialize(context) {
        const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        if (!workspaceRoot) {
            throw new Error('No workspace folder found');
        }

        this.workspaceRoot = workspaceRoot;
        await this.analyzer.initialize(workspaceRoot);
        this.context = context;
        return this;
    }

    // 项目分析
    async analyzeProject() {
        // 获取项目状态，包含文件结构和代码文件内容
        const projectState = await this.analyzer.getProjectState();
        
        // 从项目状态中提取文件结构和文件列表
        const structure = projectState.structure;
        const files = projectState.files.filter(f => f !== null).map(f => f.path);
        
        // 分析项目上下文
        const projectContext = await this.buildProjectContext(files);
        
        const analysis = {
            structure,
            files,
            context: projectContext,
            summary: {
                totalFiles: files.length,
                fileTypes: this.getFileTypeSummary(files)
            }
        };

        return analysis;
    }

    // 构建项目上下文
    async buildProjectContext(files) {
        const context = {
            dependencies: {},
            imports: new Set(),
            declarations: new Set(),
            fileTypes: new Set()
        };

        for (const file of files) {
            try {
                const fileAnalysis = await this.analyzer.analyzeFile(file);
                if (fileAnalysis) {
                    this.updateContext(context, fileAnalysis);
                }
            } catch (error) {
                console.error(`Error analyzing file ${file}:`, error);
            }
        }

        // 将Set转换为数组，便于序列化
        return {
            dependencies: context.dependencies,
            imports: Array.from(context.imports),
            declarations: Array.from(context.declarations),
            fileTypes: Array.from(context.fileTypes)
        };
    }


    // 流式响应处理
    async streamResponseWithAI(prompt, context, onData) {
        const enhancedContext = {
            ...context,
            projectContext: this.context
        };
        return this.aiService.streamResponse(prompt, enhancedContext, onData);
    }


    // 辅助函数
    getFileTypeSummary(files) {
        const summary = {};
        files.forEach(file => {
            const ext = file.split('.').pop();
            summary[ext] = (summary[ext] || 0) + 1;
        });
        return summary;
    }

    updateContext(context, fileAnalysis) {
        // 检查并提取文件类型
        const ext = fileAnalysis.path.split('.').pop();
        if (ext) {
            context.fileTypes.add(ext);
        }

        // 提取文件内容中的依赖信息（简单实现）
        const content = fileAnalysis.content || '';

        // 检测导入语句
        const importRegex = /import\s+.*?from\s+['"](.+?)['"];?/g;
        let match;
        while ((match = importRegex.exec(content)) !== null) {
            context.imports.add(match[1]);
        }

        // 检测依赖项（简化为检测package.json）
        if (fileAnalysis.path.endsWith('package.json')) {
            try {
                const packageData = JSON.parse(content);
                if (packageData.dependencies) {
                    Object.assign(context.dependencies, packageData.dependencies);
                }
                if (packageData.devDependencies) {
                    Object.assign(context.dependencies, packageData.devDependencies);
                }
            } catch (e) {
                console.error('Error parsing package.json:', e);
            }
        }

        // 检测声明（函数、类等）
        const declarationRegex = /(function|class|const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;
        while ((match = declarationRegex.exec(content)) !== null) {
            context.declarations.add(match[2]);
        }
    }
}

module.exports = AgentManager;